/**
 * 
 */
package com.iwords.web.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



/**
 * @author       BOLIN.HBC 
 * @time         2011-4-8    
 * @description  安全验证的filter       
 */
@WebFilter(filterName = "loginFilter", urlPatterns = { "/*" })
public class LoginFilter implements Filter {

	private static List<String> WRITE_KEY_JSP=new ArrayList<String>();
	
	static{
		WRITE_KEY_JSP.add("index.jsp");
		WRITE_KEY_JSP.add("login.jsp");
		WRITE_KEY_JSP.add("error.jsp");
		WRITE_KEY_JSP.add("register.jsp");
		WRITE_KEY_JSP.add("iwords");
		WRITE_KEY_JSP.add("index");
	}
	public void destroy() {

	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {

		if (process(req, res)) {
			filterChain.doFilter(req, res);
		} else {
			return;
		}
	}

	private boolean process(ServletRequest req, ServletResponse res) {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		String url = request.getRequestURL().toString();
		boolean isOk = false;

		for (String k : WRITE_KEY_JSP) {

			if (url.lastIndexOf(k) > -1) {
				isOk = true;
			}
		}

		if (!isOk) {
			if (request.getSession().getAttribute("user") == null) {
				try {
					response.sendRedirect("index");

				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				isOk = true;
			}

		}
		return isOk;

	}

	public void init(FilterConfig arg0) throws ServletException {

	}

}
